package com.example.wzh.robotsdemo;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;

import com.efrobot.library.speechsdk.SpeechManager;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.IOException;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MyService extends Service {

    public static final String TAG = "MyService";

    private ScheduledThreadPoolExecutor executor;
    private OkHttpClient client;
    private SharedPreferences sp;
    private int selecttype;
    private String url;


    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate() executed");

        Toast.makeText(this, "服务已开启", Toast.LENGTH_SHORT).show();

    }

    private void getTokenLogin() {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                User user = new User(LoginUtils.USER_NAME, LoginUtils.PASS_WORD, LoginUtils.LANG);
                Log.e(TAG,"USERJson===" + user);
                String post = post(LoginUtils.LOGIN_URL, user.toString());
                emitter.onNext(post);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String string) throws Exception {
                        Log.e(TAG,"登录的联网成功" + string);
                        LoginBean bean = new Gson().fromJson(string, LoginBean.class);
                        String token = bean.getToken();
                        Log.e(TAG,"token+++===" + token);
                        //获取token存入内存
                        sp = getSharedPreferences("sp_file", Context.MODE_PRIVATE);
                        sp.edit().putString("token",token).commit();

//                        sp = getSharedPreferences("sp_file", Context.MODE_PRIVATE);
                        String token111=sp.getString("token",null);
                        Log.e(TAG,"token111===" + token111);

                    }
                });
    }

    String post(String url, String json) throws IOException {
        Log.e(TAG,json);
        RequestBody body = RequestBody.create(MediaType.parse(LoginUtils.CONTENT_TYPE),json);

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Accept", LoginUtils.ACCEPT)
                .addHeader("X-Gizwits-Application-Id",LoginUtils.APPID)
                .build();
        Response response = client.newCall(request).execute();
        Log.e(TAG,"okhttp-----" + request);
        return response.body().string();
    }

    private void zuce() {
        //注册服务接口
        SpeechManager.getInstance().registerSpeechListener(new SpeechManager.ISpeech() {
            @Override
            public void onRegisterSuccess() {
                Log.i(TAG, "第三方收到：注册成功");
                //收到此回调时才能进行设置数据，不然设置不成功，会抛出异常
                //得到字段字符串
                String str = getStringData();
                //设置数据
                try {
                    SpeechManager.getInstance().setData(MyService.this,str);
                    Log.e(TAG,"注册成功收到的命令串" + str);
                    //开启语音识别
                    SpeechManager.getInstance().openSpeechDiscern(MyService.this);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRegisterFail() {
                Log.i(TAG, "第三方收到：注册失败");
            }
        });
    }

    @NonNull
    private String getStringData() {
        String str = "[" +
                "{\"code\":\"1000\",\"ins\":\"拉开窗帘\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"窗帘已拉开\",\"type\":\"0\"}" +
                ",{\"code\":\"1001\",\"ins\":\"把窗帘拉开\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"窗帘已拉开\",\"type\":\"0\"}" +
                ",{\"code\":\"1002\",\"ins\":\"把窗帘拉上\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"好的马上去\",\"type\":\"0\"}" +
                ",{\"code\":\"1003\",\"ins\":\"把窗帘合上\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"好的马上去\",\"type\":\"0\"}" +
                ",{\"code\":\"1004\",\"ins\":\"打开空气净化\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"空气净化已开\",\"type\":\"0\"}" +
                ",{\"code\":\"1005\",\"ins\":\"开启空气净化\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"空气净化已开\",\"type\":\"0\"}" +
                ",{\"code\":\"1006\",\"ins\":\"关闭空气净化\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"空气净化已关\",\"type\":\"0\"}" +
                ",{\"code\":\"1007\",\"ins\":\"开灯\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"小胖这就去\",\"type\":\"0\"}" +
                ",{\"code\":\"1008\",\"ins\":\"把灯打开\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"小胖这就去\",\"type\":\"0\"}" +
                ",{\"code\":\"1010\",\"ins\":\"关灯\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"灯光已关\",\"type\":\"0\"}" +
                ",{\"code\":\"1011\",\"ins\":\"把灯关上\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"灯光已关\",\"type\":\"0\"}" +
                ",{\"code\":\"1013\",\"ins\":\"开启安全模式\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"武警小胖已上线\",\"type\":\"0\"}" +
                ",{\"code\":\"1014\",\"ins\":\"关闭安全模式\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"武警小胖下线啦\",\"type\":\"0\"}" +
                ",{\"code\":\"1015\",\"ins\":\"回家\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"欢迎主人回家\",\"type\":\"0\"}" +
                ",{\"code\":\"1016\",\"ins\":\"芝麻开门\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"欢迎主人回家\",\"type\":\"0\"}" +
                ",{\"code\":\"1017\",\"ins\":\"外出\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"记得早点回来哦\",\"type\":\"0\"}" +
                ",{\"code\":\"1018\",\"ins\":\"芝麻关门\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"记得早点回来哦\",\"type\":\"0\"}" +
                ",{\"code\":\"1019\",\"ins\":\"打开加湿器\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"加湿器已开\",\"type\":\"0\"}" +
                ",{\"code\":\"1020\",\"ins\":\"关闭加湿器\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"加湿器已关\",\"type\":\"0\"}" +
                ",{\"code\":\"1021\",\"ins\":\"介绍一下公司\",\"packageName\":\"com.example.wzh.robotsdemo\",\"reply\":\"尊敬的来宾朋友，你们好！欢迎光临北京王府科技智能家居体验馆，我是王府小胖，很高兴为您服务！在这里，您将会看到充满现代科技元素的健康生态居室，体验智能家居提供舒适、便捷的生活与办公服务，享受安全无忧的舒心环境；期待您的体验，请为我点赞！\",\"type\":\"0\"}" +
                "]";
        Log.e("TAA","命令串" + str);
        return str;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand() executed");
        selecttype = intent.getIntExtra("type", -1);
        Log.e(TAG,"selecttype===" + selecttype);

        sp = getSharedPreferences("sp_file", Context.MODE_PRIVATE);
        sp.edit().putInt("selecttype",selecttype).commit();

        int selecttype111=sp.getInt("selecttype",-1);
        Log.e(TAG,"selecttype===" + selecttype111);


        //判断当前选择了那个房间
        if(selecttype == 0) {
            //选择了合肥样板间1
            url =LoginUtils.URL;
        }else if(selecttype == 1) {
            //选择了合肥样板间2
            url =LoginUtils.URL2;
        }else if(selecttype == 2) {
            //选择了合肥样板间3
            url =LoginUtils.URL3;
        }else if(selecttype == 3) {
            //选择了月星1层
            url =LoginUtils.URL4;
        }else if(selecttype == 4) {
            //选择了月星3层
            url =LoginUtils.URL5;
        }else if(selecttype == 5) {
            //选择了武汉样板间
            url =LoginUtils.URL6;
        }


        //创建计划线程池执行任务
        //显示主屏数据---MyRunnable
        executor = new ScheduledThreadPoolExecutor(1);
        //每10秒更新一次数据
        executor.scheduleWithFixedDelay(new MyRunnable(), 0, 10, TimeUnit.SECONDS);
        client = new OkHttpClient();
        //登录获取Token，存入内存
        getTokenLogin();
        //注册语音识别SDK
        zuce();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "服务已关闭", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "onDestroy() executed");
        executor.shutdown();
        try {
           SpeechManager.getInstance().unRegisterSpeechListener(this);
            //扣盖时不影响使用
            SpeechManager.getInstance().setKeepAppAlive (this);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    class MyRunnable implements Runnable {
        @Override
        public void run() {
            Log.e(TAG,"selecttype===" + selecttype);

            if (url == null) {
                return;
            }

            OkHttpUtils.get()
                    .url(url)
                    .addHeader("Accept", LoginUtils.ACCEPT)
                    .addHeader("X-Gizwits-Application-Id", LoginUtils.APPID)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.e(TAG, "联网失败" + e.getMessage());
                        }
                        @Override
                        public void onResponse(String response, int id) {
                            UBean bean = new Gson().fromJson(response, UBean.class);
                            UBean.AttrBean datas = bean.getAttr();
                            String did = bean.getDid();
//                            SpUtils.putString(MyService.this,"did",did);
//                            Log.e(TAG, "DID===" + did);
                            if (datas != null) {
                                int room1_modbus_temperature_sensor = datas.getRoom1_modbus_temperature_sensor();
                                int room1_modbus_co2_sensor = datas.getRoom1_modbus_co2_sensor();
                                int room1_modbus_pm25_sensor = datas.getRoom1_modbus_pm25_sensor();
                                int room1_modbus_voc_sensor = datas.getRoom1_modbus_voc_sensor();
                                int room1_modbus_humidity_sensor = datas.getRoom1_modbus_humidity_sensor();
                                int room1_modbus_HCHO_sensor = datas.getRoom1_modbus_HCHO_sensor();
                                Log.e(TAG, "room1_modbus_temperature_sensor===" + room1_modbus_temperature_sensor);
                                Log.e(TAG, "room1_modbus_co2_sensor===" + room1_modbus_co2_sensor);
                                Log.e(TAG, "room1_modbus_pm25_sensor===" + room1_modbus_pm25_sensor);
                                Log.e(TAG, "room1_modbus_voc_sensor===" + room1_modbus_voc_sensor);
                                Log.e(TAG, "room1_modbus_humidity_sensor===" + room1_modbus_humidity_sensor);
                                Log.e(TAG, "room1_modbus_HCHO_sensor===" + room1_modbus_HCHO_sensor);
////                                //通过本地广播发送更新数据信息
                                Intent intent = new Intent("com.example.wzh.robotsdemo.MainActivity.MyReceiver");
                                intent.putExtra("room1_modbus_temperature_sensor", room1_modbus_temperature_sensor);
                                intent.putExtra("room1_modbus_co2_sensor", room1_modbus_co2_sensor);
                                intent.putExtra("room1_modbus_pm25_sensor", room1_modbus_pm25_sensor);
                                intent.putExtra("room1_modbus_voc_sensor", room1_modbus_voc_sensor);
                                intent.putExtra("room1_modbus_humidity_sensor", room1_modbus_humidity_sensor);
                                intent.putExtra("room1_modbus_HCHO_sensor", room1_modbus_HCHO_sensor);
                                LocalBroadcastManager.getInstance(MyService.this).sendBroadcast(intent);
                            }
                        }
                    });
        }
    }



//    private void getLogInData() {
//        LoginGinseng loginGinseng = new LoginGinseng();
//        loginGinseng.setMobile(username);
//        loginGinseng.setPassword(password);
//        loginGinseng.setHouse_type("1");
//        Retrofit retrofit = new Retrofit.Builder()
//                .baseUrl(Httputils.HOSTUTIL_HTTPS)
//                .addConverterFactory(GsonConverterFactory.create())
//                .client(RetrofitAPIManager.getOkHttpClient(getApplicationContext()))
//                .build();
//        HttpInterface httpInterface = retrofit.create(HttpInterface.class);
//        Call<ResultBean> call = httpInterface.getLogIn(loginGinseng);
//        call.enqueue(new Callback<ResultBean>() {
//            @Override
//            public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
//                ResultBean r = response.body();
////                                //TODO: 验证  如果成功继续，如果失败重新登录
//                if (r != null) {
//                    Log.i(TAG, "onResponse: " + response.body());
//                    if (r.getCode() != null && r.getCode() == Constant.HttpURL.ErrorCode.OK) {
//                        PreferenceUtil.putString(Constant.UserManager.USERNAME, username);
//                        PreferenceUtil.putString(Constant.UserManager.PASSWORD, password);
//                        userProfileBean = new UserProfileBean();
//                        userProfileBean = GsonTools.getBean(GsonTools.GsonToString(r.getResult()), UserProfileBean.class);
//
//                        //保存token
//                        PreferenceUtil.putString("accessToken", userProfileBean.getOauth().getAccessToken());
//                        PreferenceUtil.putString("refreshToken", userProfileBean.getOauth().getRefreshToken());
//                        PreferenceUtil.putString("tokenType", userProfileBean.getOauth().getTokenType());
//                        PreferenceUtil.putInt("expiresIn", userProfileBean.getOauth().getExpiresIn());
//                        /*这是保存的 用户信息*/
//                        PreferenceUtil.putString("user_profile", GsonTools.GsonToString(r.getResult()));
//                        /*保存 到内存*/
//                        GizwitHolders.getInstance().setUserProfileBean(userProfileBean);
//                        if (userProfileBean.getHouses().size() <= 0) { //没有房间信息，需要扫描添加
//                            Intent intent = new Intent(mContext, HouseManagementActivity.class);
//                            intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
//                            startActivity(intent);
//                            return;
//                        } else { //有房间信息
//                            int defaultHouseID = PreferenceUtil.getInt("default_house", -1);
//                            Houses houses = null;
//                            int houseTag = 0;
//                            if (defaultHouseID == -1) {
//                                houses = userProfileBean.getHouses().get(0);
//                            } else {
//                                for (int i = 0; i < userProfileBean.getHouses().size(); i++) {
//                                    if (userProfileBean.getHouses().get(i).getId() == defaultHouseID) {
//                                        houses = userProfileBean.getHouses().get(i);
//                                        houseTag = i;
//                                    }
//                                }
//                                if (houses == null) {
//                                    houses = userProfileBean.getHouses().get(0);//houses = userProfileBean.getHouses().get(0);
//                                    houseTag = 0;
//                                }
//                            }
//                            GizwitHolders.getInstance().setProductKey(houses.getGateways().get(0).getExtid());
//
//                            PreferenceUtil.putInt("default_house", houses.getId());
//                            PreferenceUtil.putString("rolse", houses.getRole());
//
//                            PreferenceUtil.putString("product_city", houses.getCity());
//                            PreferenceUtil.putString("product_address", houses.getAddress());
//
//                            DescriPtion descriPtion = gson.fromJson(houses.getGateways().get(0).getDescription(), DescriPtion.class);
//                            PreferenceUtil.putString("product_key", descriPtion.getProductKey());
//                            PreferenceUtil.putString("productSecret", descriPtion.getProductSecret());
//                            PreferenceUtil.putString("mac", descriPtion.getMac());
//                            PreferenceUtil.putString("AppId", descriPtion.getAppId());
//                            PreferenceUtil.putString("AppSecret", descriPtion.getAppSecret());
//
//                            PreferenceUtil.putString(Constant.HouseSystemManager.CITY, houses.getCity());
//                            PreferenceUtil.putString(Constant.HouseSystemManager.ADDRESS, houses.getAddress());
//                            Set<String> tags = new HashSet<String>(); //tag--product_key
//                            for (Houses houses1 : userProfileBean.getHouses()) {
//                                tags.add( houses1.getGateways().get(0).getExtid());
//                            }
//
//                            JPushInterface.setAliasAndTags(LoginActivity.this, null, tags, new TagAliasCallback() {
//                                @Override
//                                public void gotResult(int i, String s, Set<String> set) {
//
//                                }
//                            });
//                        }
//                        //TODO:登录机智云
//                        mHandler.sendEmptyMessage(GIZWITZ_USER_LOGIN);
//                    } else {
//                        Toast.makeText(mContext, r.getMessage(), Toast.LENGTH_SHORT).show();
//                        mHandler.sendEmptyMessage(ERROR_STATE);
//                    }
//                } else {
//                    kProgressHUD.dismiss();
//                    AppUtils.show(LoginActivity.this, "请求失败");
//                }
//            }
//
//            @Override
//            public void onFailure(Call<ResultBean> call, Throwable t) {
//                Toast.makeText(mContext, "登录失败", Toast.LENGTH_SHORT).show();
//                mHandler.sendEmptyMessage(ERROR_STATE);
//            }
//        });
//
//    }


}
